//
//  NetworkTools.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/7.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import AFNetworking
//HTTP 请求方法枚举
enum WKRequsetMethod: String{
    
    case GET = "GET"
    case POST = "POST"
    
}
class NetworkTools: AFHTTPSessionManager {

    // MARK: - 应用程序信息
    private let appKey = "237409787"
    private let appSecret = "9b0afc8236b1ad78201ab96e75edc29e"
    private let redirectUrl = "http://www.baidu.com"
    
    
    //起别名
    typealias WKRequsetCallBack = (result: AnyObject?, error: NSError?) -> ()
    
    
    
    //创建单例
    static let sharedTools: NetworkTools = {
    
        let tools = NetworkTools(baseURL: nil)
    
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    
    }()
    
}

//MARK - 发布微博
extension NetworkTools {

    func sendStatus(status: String, image: UIImage?, finished: WKRequsetCallBack){
    
        //创建参数字典
        var params = [String: AnyObject]()
        
        //设置参数
        params["status"] = status
        
        //3.判断是否上传图片
        if image == nil {
        
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
        
        }else {
        
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let data = UIImagePNGRepresentation(image!)
            
            upload(urlString, data: data!, name: "pic", parameters: params, finished: finished)
        }
    
    
    }

}


// MARK: - 微博相关方法
extension NetworkTools {
    
    func loadStatus(since_id since_id: Int, max_id: Int, finished: WKRequsetCallBack) {
    
//        // 1. 获取 token 字典
//        guard var params = tokenDict else {
//            
//            // 如果字典为 nil，通知调用方，token 无效
//            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
//            
//            return
//        }
        
        //1.创建参数字典
        var params = [String: AnyObject]()
    
        // 判断是否下拉
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {  // 上拉参数
            params["max_id"] = max_id - 1
        }
        
        //准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //发送请求
          tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
    
    }
}



// MARK: - 用户相关方法
extension NetworkTools {
    
    /// 加载用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter finished:    完成回调
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, finished: WKRequsetCallBack) {
        
//        // 1. 获取 token 字典
//        guard var params = tokenDict else {
//            
//            // 如果字典为 nil，通知调用方，token 无效
//            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
//            
//            return
//        }
        //1.创建参数字典
        var params = [String: AnyObject]()
        
        
        // 2. 处理网络参数
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        params["uid"] = uid
        
         tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

// MARK: - 授权OAuth方法
extension NetworkTools {

    var oauthURL: NSURL {
        //237409787  9b0afc8236b1ad78201ab96e75edc29e
        //https://api.weibo.com/oauth2/authorize?client_id=237409787&redirect_uri=http://www.baidu.com
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
    
        return NSURL(string: urlString)!
    
    }
    
    
//    //返回一个token字典
//    private var tokenDict: [String: AnyObject]? {
//    
//        //判断token是否有效
//        if let token = UserAccountViewModel.sharedUserAccount.accessToken{
//        
//            return ["access_token": token]
//            
//        }
//    
//            return nil
//    }

    /// 加载 AccessToken
    func loadAccessToken(code: String, finished: WKRequsetCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
    }


}

//封装AFN网络方法
extension NetworkTools {
    
    private func appendToken(inout parameters: [String: AnyObject]?) -> Bool {
    
        //1.判断 token 是否为空
        guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
        
            return false
        }

        // 判断参数字典是否有值
        if parameters == nil {
        
            parameters = [String: AnyObject]()
        
        }
        
        //设置token
        parameters!["access_token"] = token
    
        return true
        
    }
    
    private func tokenRequest(method: WKRequsetMethod, URLString: String, var parameters: [String: AnyObject]?, finished: WKRequsetCallBack) {
        
        // 1> 如果追加 token 失败，直接返回
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        
        // 2. 发起网络请求
        request(method, URLString: URLString, parameters: parameters, finished: finished)
    }
    
    

    private func request(method: WKRequsetMethod, URLString: String, parameters: [String: AnyObject]?, finished:WKRequsetCallBack){
    
        
        //定义成功回调
        let sucess = {(task: NSURLSessionDataTask,result: AnyObject) -> Void in
        
            finished(result: result, error: nil)
            
        }
        
        //定义失败回调
        let failure = {(task: NSURLSessionDataTask?,error: NSError) -> Void in
        
            print(error)
        
            finished(result: nil, error: error)
        }
        
        
        if method == WKRequsetMethod.GET{
        
            GET(URLString, parameters: parameters, success: sucess, failure: failure)
        
        }else {
        
            POST(URLString, parameters: parameters, success: sucess, failure: failure)
        
        }
        
        
        }
    
    ///上传文件
    private func upload(URLString: String, data: NSData, name: String, var parameters: [String: AnyObject]?, finished: WKRequsetCallBack) {
    
        //1.追加token失败
        if !appendToken(&parameters) {
        
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
    
        
        //上传文件
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            }, success: { (_, result) -> Void in
                
                finished(result: result, error: nil)
                
            }) { (_, error) -> Void in
                
                print(error)
                
                finished(result: nil, error: error)
        }
    
    }
    
}

